<?php
/**
 * 数据源管理器.
 * 
 * 负责维护它管理的所有数据源的事务同步
 * 
 * @author Leo Ning <leo.ning@like18.com>
 * @abstract 
 * @version 1.0
 * @since 1.0
 * @copyright 2008-2011 LIKE18 INC.
 * @package model
 */
class DataSourceManager {
	private $connections = array ();
	public function __construct($connections = array()) {
		if (! empty ( $connections )) {
			foreach ( $connections as $c ) {
				$c->setDsm ( $this );
			}
			$this->connections = $connections;
		}
	}
	/**
	 * 开启一个新事务
	 * @return boolean
	 */
	public function begin() {
		foreach ( $this->connections as $con ) {
			if (! $con->begin ()) {
				return false;
			}
		}
		return true;
	}
	/**
	 * 提交事务
	 * @return boolean
	 */
	public function commit() {
		foreach ( $this->connections as $con ) {
			if (! $con->commit ()) {
				return false;
			}
		}
		return true;
	}
	/**
	 * 回滚事务
	 * @return boolean
	 */
	public function rollback() {
		foreach ( $this->connections as $con ) {
			if (! $con->rollback ()) {
				return false;
			}
		}
		return true;
	}
	/**
	 * 得到一个数据源
	 * @param string $name
	 * @return DataSource 
	 */
	public function getDataSource($name) {
		global $cfg_opts;
		if (isset ( $this->connections [$name] )) {
			return $this->connections [$name];
		} else if (isset ( $cfg_opts ['ds'] [$name] )) {
			$opts = $cfg_opts ['ds'] [$name];
			$driver = $opts ['driver'] . 'Datasource';
			if (class_exists ( $driver )) {
				$ds = new $driver ( $opts );
				if ($ds->connect ()) {
					$ds->setDsm ( $this );
					$this->connections [$name] = $ds;
					return $this->connections [$name];
				}
			}
		}
		return NULL;
	}
	/**
	 * 设置数据源
	 * @param array $connections map
	 */
	public function setDataSources($connections = array()) {
		if (! empty ( $connections )) {
			foreach ( $connections as $c ) {
				$c->setDsm ( $this );
			}
		}
		$this->connections = array_merge ( $this->connections, $connections );
	}
	/**
	 * 移除一个名为$name的数据源
	 * @param string $name 数据源的名称
	 */
	public function removeDataSource($name) {
		if (isset ( $this->connections [$name] )) {
			$this->connections [$name]->discounect ();
			$this->connections [$name] = null;
			unset ( $this->connections [$name] );
		}
	}

}